package com.edgclub.edg.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.GroupDetailsActivity;
import com.edgclub.edg.adapter.GroupAdapter;
import com.edgclub.edg.adapter.adapteruitls.MyItemClickListener;
import com.edgclub.edg.api.FriendApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.param.MessageParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.GroupBean;
import com.edgclub.edg.model.result.GroupListData;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.easeui.dao.DaoHelper;
import com.hyphenate.easeui.dao.GroupChatBeanDao;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class GroupListFragment extends GzBaseFragment implements View.OnClickListener ,VolleyListener{

	private static final String TOPIC_TYPE = "topic_type";
	private Activity mActivity;

	private int currPage = 1;
	private int pageSize = 20;
	private XRecyclerView recyclerView;
	private GroupAdapter groupAdapter;

	private UserPrefUtils userPrefUtils;
	private boolean isFirstLoad = true;
	private boolean isLoading = false;
	private FriendApi friendApi;

	private List<GroupBean> groupBeanList;


	public static GroupListFragment newInstance(String topic_type) {
		GroupListFragment f = new GroupListFragment();
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		mActivity = this.getActivity();
		return inflater.inflate(R.layout.fragment_bb, container, false);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		friendApi=new FriendApi(getActivity());
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).register(this);

	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initView(view);
		initData();
//		if(currPage==1)
//			getGroupPost(currPage);
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			if (recyclerView != null && isFirstLoad) {
				isFirstLoad = false;
				getGroupPost(currPage);

			}
			if(recyclerView!=null){
				MobclickAgent.onEvent(getActivity(),"EC_BB_GROUP");
			}
		}
	}


	private void initView(View view){
		initLoadView(view);
		recyclerView = (XRecyclerView) view.findViewById(R.id.recyclerview);
		LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		recyclerView.setLayoutManager(layoutManager);

		recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
			@Override
			public void onRefresh() {
				currPage = 1;
				getGroupPost(currPage);
			}

			@Override
			public void onLoadMore() {
				getGroupPost(currPage);
			}
		});

	}

	private void initData(){
		userPrefUtils = new UserPrefUtils(getActivity());
		groupBeanList=new ArrayList<>();
		groupAdapter=new GroupAdapter(getActivity());
		groupAdapter.setDatas(groupBeanList);
		recyclerView.setAdapter(groupAdapter);

		groupAdapter.setOnItemClickListener(new MyItemClickListener() {
			@Override
			public void onItemClick(View view, int postion) {
				Intent intent=new Intent(getActivity(), GroupDetailsActivity.class);
				intent.putExtra("groupid",groupBeanList.get(postion).getGroupid());
				intent.putExtra("groupname",groupBeanList.get(postion).getGname());
				startActivity(intent);
			}
		});
	}
	private void getGroupPost(int page) {
		if(isLoading){
			return;
		}
		MessageParam myParam = new MessageParam();
		myParam.setPage(page + "");
		myParam.setPageSize(pageSize + "");
		myParam.setUserId(userPrefUtils.getUser().getId() + "");
		friendApi.getAllGroupList(myParam,this);
	}



	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_refresh:
				break;

		}
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).unregister(this);
	}

	@Override
	public void onStart(String tag) {
		isLoading=true;
	}

	@Override
	public void onSuccess(String response, String tag) {
		isLoading=false;
		recyclerView.refreshComplete();
		recyclerView.loadMoreComplete();
		setLoadViewGONE();
		if (JSONHelper.isSuccess(response)) {
			GroupListData data = JsonUtil.getMode(response,
					GroupListData.class);
			if(null!=data.getData() && data.getData().size()>0) {
				if (currPage == 1) {
					groupBeanList.clear();
				}
				currPage++;
				groupBeanList.addAll(data.getData());
				groupAdapter.notifyDataSetChanged();
				for(GroupBean groupBean:groupBeanList){
					if(!DaoHelper.getInstance(getActivity(),Constant.DB_NAME_GROUP).isHas(GroupChatBeanDao.Properties.Ggimid,groupBean.getGimid()))
					DaoHelper.getInstance(getActivity(), Constant.DB_NAME_GROUP).insert(groupBean);
				}
			}else{
				recyclerView.noMoreLoading();
			}
		}

	}

	@Override
	public void onFaile(VolleyError volleyError, String tag) {
		isLoading=false;
		recyclerView.refreshComplete();
		recyclerView.loadMoreComplete();
		ResultCode.toastVolleyError(getActivity(), volleyError);
		setNoNetWork(new ReLoadClickListener() {
			@Override
			public void reload() {
				getGroupPost(currPage);
			}
		});
	}

	@Subscribe
	public void refreshListView(HashMap<String, Object> map){
		String event = (String) map.get("event");
		if (null!=event&&BroadCastEvent.BB_GROUP_REFUL.equals(event)) {
			currPage=1;
			getGroupPost(currPage);
		}
	}

}
